package cm.netease;

import cm.config.MchProperties;
import cm.constant.MchPropertiesDTO;

import cm.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.apache.http.impl.client.CloseableHttpClient;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class NeteaseUtils {
    //创建网易云信账号
    private static final String CREATE_URL = "https://api.netease.im/nimserver/user/create.action";
    //发送
    private static final String SEND_URL = "https://api.netease.im/nimserver/msg/sendMsg.action";
    //推送
    private static final String PUSH_URL = "https://api.netease.im/nimserver/msg/sendAttachMsg.action";
    //历史记录
    private static final String HISTORY_URL = "https://api.netease.im/nimserver/history/querySessionMsg.action";


    @Value("netease.defaultPassword:123456")
    private String defaultPassword;

    @Autowired
    MchProperties mchProperties;

    public String createAccid(String accid,String name,String id) throws Exception{
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpPost post = getPost(CREATE_URL,id);
        //设置请求参数
        List<NameValuePair> nameValuePairList = new ArrayList<>();
        nameValuePairList.add(new BasicNameValuePair("accid",accid));
        nameValuePairList.add(new BasicNameValuePair("name",name));
        String token = MD5Util.getMD5(defaultPassword);
        nameValuePairList.add(new BasicNameValuePair("token",token));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairList,"UTF-8"));
        //执行请求
        HttpResponse httpResponse = closeableHttpClient.execute(post);
        //返回结果
        String result = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
        log.info(result);
        return accid;
    }
    private HttpPost getPost(String url,String id){
        MchPropertiesDTO mchPropertiesDTO = mchProperties.getMchById(id);
        HttpPost httpPost = new HttpPost(url);
        String curTime = String.valueOf(System.currentTimeMillis()/1000L);
        String noce = String.valueOf((int)(Math.random()*9+1)*1000);
        String checkNum = CheckSumBuilder.getCheckSum(mchPropertiesDTO.getSec(),noce,curTime);
        //设置请求header
        httpPost.addHeader("Appkey",mchPropertiesDTO.getKey());
        httpPost.addHeader("Noce",noce);
        httpPost.addHeader("curTime",curTime);
        httpPost.addHeader("checkNum",checkNum);
        httpPost.addHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");
        return httpPost;
    }
}
